<template>
    <div v-if="hasData" class="chart-container-7">
        <div :class="className" :id="id" :style="{height:height,width:width}"></div>
        <div class="legend">
            <div class="single-item">
                <div class="item item1">

                </div>
                Satisfactory Rewards Delivered

            </div>
            <div class="single-item">
                <div class="item item2">

                </div>
                Delayed  Rewards Delivered

            </div>
            <div class="single-item">
                <div class="item item3">

                </div>
                Undesired Rewards Delivered

            </div>
            <div class="single-item">
                <div class="item item4">

                </div>
                Delayed and Undesired Rewards Delivered

            </div>
            <div class="single-item">
                <div class="item item5">

                </div>
                Rewards Undelivered

            </div>

            <div class="single-item">
                <div class="item item6">

                </div>
                Work in Progress

            </div>
        </div>
    </div>

    <div v-else>
        <div class="no-data">
            The Fundraiser is New to the Platform
        </div>
    </div>

</template>

<script>
    import echarts from "echarts";
    import {feature7Data} from "@/api/feature";
    import {mapState, mapMutations} from "vuex";

    export default {
        props: {
            className: {
                type: String,
                default: "chart"
            },
            id: {
                type: String,
                default: "chart"
            },
            width: {
                type: String,
                default: "200px"
            },
            height: {
                type: String,
                default: "500px"
            }
        },
        data() {
            return {
                chart: null,
                featureData: [],
                hasData: true
            };
        },
        watch: {
            canDraw(val) {
                if (val) {
                    console.log("feature7");
                    this.initChart();
                }
            }
        },
        computed: {
            ...mapState({
                currentCampainId: state => state.campaign.currentCampainId,
                currentCampainCategory: state => state.campaign.currentCampainCategory,
                canDraw: state => state.campaign.canDraw
            })
        },
        mounted() {
            // this.initChart();
            if(this.canDraw) {
                this.initChart();
            }
        },
        beforeDestroy() {
            if (!this.chart) {
                return;
            }
            this.chart.dispose();
            this.chart = null;
        },
        methods: {
            async initChart() {
                var that = this

                this.chart = echarts.init(document.getElementById(this.id));

                var featureServerData = await feature7Data();
                this.featureData = featureServerData[this.currentCampainId];
                // 暂时去除第一条不符合规范的数据
                // this.featureData = this.featureData.slice(1);

                console.log("********")

                if(!this.featureData) {
                    this.hasData = false;
                    return;
                }

                if (this.featureData.length == 0) {
                    this.hasData = false;
                    return;
                }


                //   console.log(this.featureData);

                var data = [];
                var dataCount = 3;
                var startTime = new Date().getTime();
                var types = [
                    {name: "Satisfactory Rewards Delivered", color: "#40b33f"},
                    {name: "Delayed Rewards Delivered", color: "#c9c691 "},
                    {name: "Undesired Rewards Delivered", color: "#e4954d "},
                    {name: "Rewards Undelivered", color: "#bf3030"},
                    {name: "Work in Progress", color: "#aaaaaa"},
                    {name: "Delayed and Undesired Rewards Delivered", color: "#c9c691"}
                ];

                var typesMap = {
                    "Satisfactory Rewards Delivered": 0,
                    "Delayed Rewards Delivered": 1,
                    "Undesired Rewards Delivered": 2,
                    "Rewards Undelivered": 3,
                    "Work in Progress": 4,
                    "Delayed and Undesired Rewards Delivered": 5
                };

                this.featureData.forEach((item, index) => {
                    // console.log(new Date(item.start_time).getTime());
                    // console.log(item.end_time);
                    // console.log(item.outcome);
                    // console.log(item.num_backers);

                    var typeItem = types[typesMap[item.outcome]];

                    if (typeItem) {
                        if (new Date(item.start_time).getTime() < startTime) {
                            startTime = new Date(item.start_time).getTime();
                        }

                        data.push({
                            name: item.outcome,
                            value: [
                                typesMap[item.outcome],
                                new Date(item.start_time).getTime(),
                                new Date(item.end_time).getTime(),
                                item.num_backers
                            ],
                            itemStyle: {
                                normal: {
                                    color: typeItem.color
                                }
                            }
                        });
                    }
                });

                //   // Generate mock data
                //   echarts.util.each(types, function(category, index) {
                //     var baseTime = startTime;
                //     for (var i = 0; i < dataCount; i++) {
                //       var typeItem = types[Math.round(Math.random() * (types.length - 1))];
                //       var duration = Math.round(Math.random() * 10000000 * 1000);
                //       var num = Math.round(Math.random() * 100);
                //       data.push({
                //         name: typeItem.name,
                //         value: [index, baseTime, (baseTime += duration), num],
                //         itemStyle: {
                //           normal: {
                //             color: typeItem.color
                //           }
                //         }
                //       });
                //       baseTime += Math.round(Math.random() * 2000);
                //     }
                //   });

                function renderItem(params, api) {
                    /*index,
                                    baseTime,
                                    baseTime += duration,
                                    duration*/

                    var categoryIndex = api.value(0);
                    var start = api.coord([api.value(1), api.value(3)]);
                    var yValue = api.value(3);
                    var size = api.size([api.value(2) - api.value(1), yValue]);
                    var style = api.style();

                    return {
                        type: "rect",
                        shape: {
                            x: start[0],
                            y: start[1],
                            width: size[0],
                            height: 3
                        },
                        style: style
                    };
                }

                var option = {
                    color: [
                        "#40b33f",
                        "#c9c691",
                        "#e4954d",
                        "#d55442",
                        "#bf3030",
                        "#aaaaaa"
                    ],
                    tooltip: {
                        formatter: function (params) {
                            let duration =
                                new Date(params.value[1]).toLocaleDateString() +
                                "~" +
                                new Date(params.value[2]).toLocaleDateString();

                            return (
                                params.marker +
                                params.name +
                                "(" +
                                duration +
                                "): " +
                                params.value[3]
                            );
                        }
                    },
                    title: {
                        text: "The fundraiser has completed " + that.featureData.length + " Campaigns",
                        left: "center"
                    },
                    grid: {
                        show: false,
                        borderWidth: 0,
                        height: 300
                    },
                    xAxis: {
                        min: startTime,
                        nameGap: 4,
                        name: "Production Timeline",
                        nameRotate: 45,
                        nameGap: 5,
                        splitLine: {
                            show: false,
                        },
                        axisLabel: {
                            formatter: function (val) {
                                return new Date(val).toLocaleDateString();
                            }
                        }
                    },
                    yAxis: {
                        splitLine: {
                            show: false,
                        },
                        scale: true,
                        name: "Number of Backers"
                        /* data: categories,
                                      axisLabel: {
                                          margin: 2,
                                          formatter: function (value, index) {
                                              console.log(value)
                                              let length = value.length
                                              return value.substr(0, 13) + "\n" + value.substr(13, length)
                                          }
                                      }*/
                    },
                    series: [
                        {
                            type: "custom",
                            renderItem: renderItem,
                            itemStyle: {
                                normal: {
                                    opacity: 0.8
                                }
                            },
                            encode: {
                                x: [1, 2],
                                y: 3
                            },

                            /*index,
                                        baseTime,
                                        baseTime += duration,
                                        duration*/

                            data: data
                        }
                    ]
                };

                this.chart.setOption(option);
            }
        }
    };
</script>

<style rel="stylesheet/scss" lang="scss">
    .no-data {
        font-size: 22px;
        font-weight: bold;
        text-align: center;
    }

    .chart-container-7 {
        position: relative;
        padding: 20px;
        width: 1200px;
        display: flex;
        .legend {
            margin-top: 66px;
            .single-item {
                display: flex;
                align-items: center;

                .item {
                    width: 26px;
                    height: 14px;
                    background-color: red;
                    margin: 16px;
                }

                .item1 {
                    background-color: #40b33f;
                }
                .item2 {
                    background-color: #c9c691;
                }
                .item3 {
                    background-color: #e4954d;
                }
                .item4 {
                    background-color: #d55442;
                }
                .item5 {
                    background-color: #bf3030;
                }
                .item6 {
                    background-color: #aaaaaa;
                }

            }
        }
    }

</style>
